<?php

namespace App\Services;

use App\Models\UserRoles;

class UserRoleService extends ServiceBase
{
    public function getOne($user_id, $server_id, $role_id)
    {
        $unique_id = UserRoleUniqueIdService::getInstance()->getOrCreateUniqueId($user_id, $server_id, $role_id);
        $role = UserRoles::whereRaw("role_unique_id={$unique_id}")->first();
        return $role;
    }

    public function getOneByUniqueId($unique_id)
    {
        $role = UserRoles::whereRaw("role_unique_id={$unique_id}")->first();
        return $role;
    }

    public function getOneByRoleId($user_id, $role_id)
    {
        $role = UserRoles::whereRaw("user_id={$user_id} AND role_id={$role_id}")->first();
        return $role;
    }

    public function paySuccess($user_id, $server_id, $role_id, $pay_time, $pay_amount)
    {
        $role = $this->getOne($user_id, $server_id, $role_id);
        if (!$role) {
            return;
        }

        // 首次充值
        if ($role->first_pay_time == 0) {
            $role->first_pay_time = $pay_time;
            $role->first_pay_amount = $pay_amount;
        }

        // 当天累计充值
        $today = date('Y-m-d', time());
        if (date('Y-m-d', $role->last_pay_time) != $today) {
            $role->today_pay_amount = 0;
        }
        if (date('Y-m-d', $pay_time) == $today) {
            $role->today_pay_amount += $pay_amount;
        }

        // last_pay_time 一定要放到 当天累计充值 的逻辑后面
        $role->last_pay_time = $pay_time;
        $role->total_pay_amount += $pay_amount;
        $role->total_pay_num += 1;
        $role->save();

        return true;
    }
}
